package com.st.valid.jsr3.customVaild.controller;
import com.alibaba.fastjson.JSON;
import com.st.valid.jsr3.customVaild.entity.CustomRequestVo;
import com.st.valid.jsr3.groupValid.mark.UpdateGroup;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
 * jsr303 自定义 控制器
 * @创建人: 放生
 * @创建时间: 2022/4/2
 */
@RestController
public class CustomVaildController {

    /**
     * 自定义注解-custom
     *
     * @param grv
     * @param result
     * @return
     */
    @PostMapping("/custom")
    public String custom(@Validated(UpdateGroup.class) @RequestBody CustomRequestVo grv, BindingResult result){
        String message = getError(result);
        return Objects.isNull(message)?"update ok":message;
    }

    public String getError(BindingResult result){
        if(result.hasErrors()){
            Map<String,String> map = new HashMap<>();
            //1、获取校验的错误结果
            result.getFieldErrors().forEach((item)->{
                //FieldError 获取到错误提示
                String message = item.getDefaultMessage();
                //获取错误的属性的名字
                String field = item.getField();
                map.put(field,message);
            });
            return JSON.toJSONString(map);
        }
        return null;
    }

}
